<template>
  <div class="merchant-management-container">
    <div class="page-header">
      <h1>商户管理</h1>
      <p>管理平台的所有商户信息，包括查看、编辑和状态管理</p>
      <a-button type="primary" @click="handleCreate">
        <template #icon>
          <PlusOutlined />
        </template>
        新增商户
      </a-button>
    </div>

    <!-- 搜索卡片 -->
    <a-card class="search-card">
      <a-form layout="inline" :model="searchParams">
        <a-form-item label="商户名称">
          <a-input
            v-model:value="searchParams.merchantName"
            placeholder="请输入商户名称"
            allow-clear
            @press-enter="handleSearch"
            style="width: 200px;"
          />
        </a-form-item>
        <a-form-item label="服务商">
          <a-select
            v-model:value="searchParams.providerId"
            placeholder="请选择服务商"
            allow-clear
            style="width: 180px;"
            show-search
            :filter-option="filterProviderOption"
          >
            <a-select-option v-for="provider in availableProviders" :key="provider.providerId" :value="provider.providerId">
              {{ provider.providerName }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="状态">
          <a-select
            v-model:value="searchParams.status"
            placeholder="请选择状态"
            allow-clear
            style="width: 120px;"
          >
            <a-select-option :value="1">启用</a-select-option>
            <a-select-option :value="0">停用</a-select-option>
            <a-select-option :value="2">审核中</a-select-option>
            <a-select-option :value="3">审核失败</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item>
          <a-space>
            <a-button type="primary" @click="handleSearch">搜索</a-button>
            <a-button @click="handleReset">重置</a-button>
          </a-space>
        </a-form-item>
      </a-form>
    </a-card>

    <!-- 数据表格 -->
    <a-card class="table-card">
      <AnyTable
        ref="merchantTable"
        :autoLoad="true"
        :dataLoader="loadMerchantData"
        :tableColumns="tableColumns"
        :searchParams="searchParams"
        :tableScroll="{ x: 1200 }"
        tableRowKey="merchantId"
        @loadComplete="handleLoadComplete"
      >
        <template #tableToolbar>
          <a-space>
            <a-button type="primary" @click="handleCreate">
              <PlusOutlined />
              新增商户
            </a-button>
            <a-button @click="handleBatchExport" :disabled="!hasData">
              <ExportOutlined />
              批量导出
            </a-button>
          </a-space>
        </template>

        <template #tableCell="{ column, record }">
          <template v-if="column.key === 'merchantInfo'">
            <div class="merchant-info">
              <div class="merchant-name">{{ record.merchantName }}</div>
              <div class="merchant-id">{{ record.merchantId }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'providerInfo'">
            <div class="provider-info">
              <a-tag color="blue">{{ getProviderName(record.providerId) }}</a-tag>
              <div class="provider-id">{{ record.providerId }}</div>
            </div>
          </template>

          <template v-else-if="column.key === 'contactInfo'">
            <div class="contact-info">
              <div class="contact-name">
                <UserOutlined style="margin-right: 4px; color: #1890ff;" />
                {{ record.contactName }}
              </div>
              <div class="contact-phone">
                <PhoneOutlined style="margin-right: 4px; color: #52c41a;" />
                {{ record.contactTelephone }}
              </div>
            </div>
          </template>

          <template v-else-if="column.key === 'status'">
            <a-tag :color="getMerchantStatusColor(record.status)">
              {{ getMerchantStatusName(record.status) }}
            </a-tag>
          </template>

          <template v-else-if="column.key === 'remark'">
            <a-tooltip :title="record.remark" v-if="record.remark">
              <span class="remark-text">{{ record.remark }}</span>
            </a-tooltip>
            <span v-else class="no-remark">暂无备注</span>
          </template>

          <template v-else-if="column.key === 'action'">
            <a-space>
              <a-button type="link" @click="handleViewDetail(record)">
                <EyeOutlined />
                查看
              </a-button>
              <a-button type="link" @click="handleEdit(record)">
                <EditOutlined />
                编辑
              </a-button>
              <a-button type="link" @click="handleToggleStatus(record)">
                <template v-if="record.status === 1">
                  <StopOutlined />
                  停用
                </template>
                <template v-else>
                  <CheckCircleOutlined />
                  启用
                </template>
              </a-button>
              <a-dropdown>
                <template #overlay>
                  <a-menu>
                    <a-menu-item @click="handleDelete(record)">
                      <DeleteOutlined style="color: #ff4d4f;" />
                      删除
                    </a-menu-item>
                    <a-menu-item @click="handleResetPassword(record)">
                      <KeyOutlined />
                      重置密码
                    </a-menu-item>
                  </a-menu>
                </template>
                <a-button type="link">
                  <MoreOutlined />
                </a-button>
              </a-dropdown>
            </a-space>
          </template>
        </template>
      </AnyTable>
    </a-card>

    <!-- 查看详情抽屉 -->
    <MerchantDetail
      ref="merchantDetailRef"
      @refresh="refreshTable"
    />

    <!-- 编辑抽屉 -->
    <MerchantEdit
      ref="merchantEditRef"
      @refresh="refreshTable"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue'
import {
  PlusOutlined,
  ExportOutlined,
  UserOutlined,
  PhoneOutlined,
  EyeOutlined,
  EditOutlined,
  StopOutlined,
  CheckCircleOutlined,
  DeleteOutlined,
  KeyOutlined,
  MoreOutlined
} from '@ant-design/icons-vue'
import {
  mockLoadMerchants,
  mockSaveMerchant,
  mockDeleteMerchant,
  getMerchantStatusName,
  getMerchantStatusColor,
  type Merchant
} from '@/mock/merchants'
import { serviceProviders } from '@/mock/service-providers'
import MerchantDetail from './merchant-detail.vue'
import MerchantEdit from './merchant-edit.vue'

const router = useRouter()

// 组件引用
const merchantTable = ref()
const merchantDetailRef = ref()
const merchantEditRef = ref()

// 搜索参数
const searchParams = reactive({
  merchantName: '',
  providerId: '',
  status: undefined
})

// 可用服务商列表
const availableProviders = ref(serviceProviders)

// 是否有数据
const hasData = ref(false)

// 表格列配置
const tableColumns = [
  {
    title: '商户信息',
    key: 'merchantInfo',
    width: 220,
    fixed: 'left'
  },
  {
    title: '服务商',
    key: 'providerInfo',
    width: 160,
    align: 'center'
  },
  {
    title: '联系信息',
    key: 'contactInfo',
    width: 180
  },
  {
    title: '状态',
    key: 'status',
    width: 100,
    align: 'center'
  },
  {
    title: '备注',
    key: 'remark',
    width: 200,
    ellipsis: true
  },
  {
    title: '创建时间',
    dataIndex: 'createdTime',
    key: 'createdTime',
    width: 160,
    align: 'center'
  },
  {
    title: '更新时间',
    dataIndex: 'updatedTime',
    key: 'updatedTime',
    width: 160,
    align: 'center'
  },
  {
    title: '操作',
    key: 'action',
    width: 180,
    align: 'center',
    fixed: 'right'
  }
]

// 数据加载函数
const loadMerchantData = async (params: any) => {
  try {
    const response = await mockLoadMerchants({
      current: params.pageNumber,
      pageSize: params.pageSize,
      merchantName: params.merchantName,
      providerId: params.providerId,
      status: params.status
    }) as any

    return {
      records: response.data,
      total: response.total
    }
  } catch (error) {
    console.error('加载商户数据失败:', error)
    throw error
  }
}

// 获取服务商名称
const getProviderName = (providerId: string) => {
  const provider = availableProviders.value.find(p => p.providerId === providerId)
  return provider ? provider.providerName : providerId
}

// 筛选服务商选项
const filterProviderOption = (input: string, option: any) => {
  const provider = availableProviders.value.find(p => p.providerId === option.value)
  return provider ? provider.providerName.toLowerCase().includes(input.toLowerCase()) : false
}

// 搜索
const handleSearch = () => {
  merchantTable.value?.resetTable()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchParams, {
    merchantName: '',
    providerId: '',
    status: undefined
  })
  merchantTable.value?.resetTable()
}

// 新增商户
const handleCreate = () => {
  router.push('/merchant-management/merchant-edit/create')
}

// 查看详情
const handleViewDetail = (record: Merchant) => {
  router.push(`/merchant-management/merchant-detail/${record.merchantId}`)
}

// 编辑商户
const handleEdit = (record: Merchant) => {
  router.push(`/merchant-management/merchant-edit/${record.merchantId}`)
}

// 切换状态
const handleToggleStatus = async (record: Merchant) => {
  const newStatus = record.status === 1 ? 0 : 1
  const action = newStatus === 1 ? '启用' : '停用'

  try {
    // 模拟API调用
    await mockSaveMerchant({ ...record, status: newStatus })
    record.status = newStatus
    message.success(`${action}商户成功`)
  } catch (error) {
    message.error(`${action}商户失败`)
  }
}

// 删除商户
const handleDelete = (record: Merchant) => {
  message.warning(`删除商户 ${record.merchantName} 功能开发中...`)
}

// 重置密码
const handleResetPassword = (record: Merchant) => {
  message.info(`重置商户 ${record.merchantName} 密码功能开发中...`)
}

// 批量导出
const handleBatchExport = () => {
  message.info('批量导出功能开发中...')
}

// 刷新表格
const refreshTable = () => {
  merchantTable.value?.refreshTable()
}

// 加载完成处理
const handleLoadComplete = () => {
  const tableData = merchantTable.value?.getTableData() || []
  hasData.value = tableData.length > 0
}

onMounted(() => {
  // 初始化
})
</script>

<style scoped>
.merchant-management-container {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.page-header p {
  margin: 5px 0 0 0;
  color: #666;
  font-size: 14px;
}

.search-card {
  margin-bottom: 16px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
}

.merchant-info {
  line-height: 1.4;
}

.merchant-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.merchant-id {
  font-size: 12px;
  color: #666;
  font-family: monospace;
}

.provider-info {
  text-align: center;
}

.provider-id {
  font-size: 11px;
  color: #999;
  margin-top: 4px;
  font-family: monospace;
}

.contact-info {
  line-height: 1.4;
}

.contact-name,
.contact-phone {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
  font-size: 13px;
}

.contact-name {
  font-weight: 500;
  color: #333;
}

.contact-phone {
  color: #666;
}

.remark-text {
  display: block;
  max-width: 180px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  color: #333;
}

.no-remark {
  color: #ccc;
  font-style: italic;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-tag {
  margin: 0;
}

@media (max-width: 768px) {
  .merchant-management-container {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }

  .search-card .ant-form {
    flex-direction: column;
  }

  .search-card .ant-form-item {
    width: 100%;
    margin-bottom: 12px;
  }

  .search-card .ant-input,
  .search-card .ant-select {
    width: 100% !important;
  }
}
</style>

